/**
 * 
 */
package cn.sccl.common.scheduler.job;

import cn.sccl.common.scheduler.JobListener;
import cn.sccl.common.scheduler.enums.JobStateEnum;
import cn.sccl.common.scheduler.model.TaskFireLog;
import cn.sccl.common.scheduler.model.TaskParams;
import cn.sccl.common.util.SpringUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 默认调度(非阻塞)
 * 
 * Created by _minus on 2017-10-04.
 */
public class BaseJob implements Job {
	private final Logger logger = LoggerFactory.getLogger(BaseJob.class);


	@Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
		long start = System.currentTimeMillis();
		JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
		String taskType = jobDataMap.getString("taskType");
		String targetObject = jobDataMap.getString("targetObject");
		String targetMethod = jobDataMap.getString("targetMethod");
		String targetParams = jobDataMap.getString("targetParams");

//		String key = targetMethod + "." + targetObject;
		TaskFireLog log = (TaskFireLog) jobDataMap.get(JobListener.JOB_LOG);

		//所执行方法的参数params
		TaskParams params = new TaskParams();
		params.setParams(targetParams);
		params.setFireLogId(log.getId());


		try {
			logger.info("定时任务{"+targetObject+"}{"+targetMethod+"}开始");

			System.out.println("*****************new task begin***************");
			System.out.println("定时任务{"+targetObject+"}{"+targetMethod+"}开始");
			try {


				log.setStatus(JobStateEnum.TASK_RUNNING.getCode().toString());//任务状态为正在执行
//				if (TaskTypeEnum.DISCOVER_TASK.getType().equals(taskType)) {
//					Object refer = Tools.getSpringUitls().getSpringBean(targetObject) ;
//					refer.getClass().getDeclaredMethod(targetMethod,TaskParams.class).invoke(refer,params);
//				}


				Object refer = SpringUtils.getSpringBean(targetObject) ;
				refer.getClass().getDeclaredMethod(targetMethod,TaskParams.class).invoke(refer,params);
				double time = (System.currentTimeMillis() - start) / 1000.0;
				logger.info("定时任务{"+targetObject+"}{"+targetMethod+"}用时："+time);

				System.out.println("定时任务{"+targetObject+"}{"+targetMethod+"}用时："+time);
				System.out.println("*****************task end***************\n");

			} finally {

			}
		} catch (Exception e) {
			//所有任务执行的方法中 所有异常全部抛出，这里统一做处理
			throw new JobExecutionException(e);
		}
	}

	private void unLock(String key) {

	}
}
